using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Input;

namespace WeChat.Controls;

[PseudoClasses(RightButtonPressed)]
public sealed class MessageContent : ContentControl
{
    private const string RightButtonPressed = ":rightButtonPressed";

    public static readonly StyledProperty<bool> IsRightProperty = AvaloniaProperty
        .Register<MessageContent,
            bool>(
            nameof(IsRight));

    /// <summary>
    /// 显示在右边
    /// </summary>
    public bool IsRight
    {
        get => GetValue(IsRightProperty);
        set => SetValue(IsRightProperty, value);
    }
    
    protected override void OnPointerPressed(PointerPressedEventArgs e)
    {
        var properties = e.GetCurrentPoint(this).Properties;

        //必须是右键单击
        if (!properties.IsRightButtonPressed)
            return;

        //必须带有菜单
        if (ContextFlyout is not MenuFlyout flyout)
            return;

        flyout.Closed += OnFlyoutClosed;

        PseudoClasses.Set(RightButtonPressed, true);
    }

    protected override void OnPointerReleased(PointerReleasedEventArgs e)
    {
        PseudoClasses.Set(RightButtonPressed, false);
    }
    
    private void OnFlyoutClosed(object? sender, EventArgs eventArgs)
    {
        if (sender is not MenuFlyout flyout)
            return;
        
        PseudoClasses.Set(RightButtonPressed, false);
        
        flyout.Closed -= OnFlyoutClosed;
    }
}